/*

* 目的：国内无法正常访问github，使用Cloudflare自定义域名代理访问，相对于github加速器
* 注意：访问普通文件和图片可以正常引用或下载，但在html中无法直接引用.js或.css，
* html中使用的静态文件，可以通过Cloudflare的pages绑定github仓库即可。

* 1. 在Github 中设置 Fine-grained tokens；
* 选择 'Only select repositories' 需要读取的私有库
* 在'Repository permissions'中选择 'contents'  Access:Read and write
* 生成token；

* 2.拷贝workers.js代码，无需更改
* 设置--变量--添加 GH_TOKEN，GH_NAME，GH_REPO，GH_BRANCH
* 部署。

* 3. 访问（GH_NAME用户，GH_REPO仓库，GH_BRANCH分支下的文件）
* https://domain/文件名
*


* 如果希望使用静态文件.js,.css之类的，可以使用Cloudflare的Pages绑定仓库，并设置自定义域名即可

*/
let token = "";
export default {
	async fetch(request, env) {
		const url = new URL(request.url);
		const pathname = url.pathname
		let githubRawUrl = ''
		if (pathname !== '/') {
			if (pathname.match(/http.?:\/\//)) {
				githubRawUrl = pathname.slice(1)
				if (!pathname.includes('github')) {
					return Response.redirect(githubRawUrl, 302)
				}
			} else {
				if (pathname.includes('/releases/download/')) {
					githubRawUrl = 'https://github.com';
				} else {
					githubRawUrl = 'https://raw.githubusercontent.com';
				}
				if (env.GH_NAME) {
					githubRawUrl += '/' + env.GH_NAME;
					if (env.GH_REPO && !pathname.match(/main|releases/)) {
						githubRawUrl += '/' + env.GH_REPO;
						if (env.GH_BRANCH) githubRawUrl += '/' + env.GH_BRANCH;
					}
				}
				githubRawUrl += pathname;
			}
			console.log(githubRawUrl);
			if (env.GH_TOKEN && env.TOKEN) {
				if (env.TOKEN == url.searchParams.get('token')) token = env.GH_TOKEN || token;
				else token = url.searchParams.get('token') || token;
			} else token = url.searchParams.get('token') || env.GH_TOKEN || env.TOKEN || token;

			const githubToken = token;
			//console.log(githubToken);
			if (!githubToken || githubToken == '') return new Response('TOKEN不能为空', { status: 400 });

			// 构建请求头
			const headers = new Headers();
			headers.append('Authorization', `token ${githubToken}`);

			// 发起请求
			const response = await fetch(githubRawUrl, { headers });

			// 检查请求是否成功 (状态码 200 到 299)
			if (response.ok) {
				return new Response(response.body, {
					status: response.status,
					headers: response.headers
				});
			} else {
				let errorInfo = {
					status: 401,
					success: false,
					token: null,
					description:['Token无效','文件路径错误'],
					accepted_requests: ['默认仓库：/FILEPATH', '指定仓库：/REPO/BRANCH/FILEPATH','完整路径：/URL', ]
				}
				// 如果请求不成功，返回适当的错误响应
				return Response.json(errorInfo);
			}

		} else {
			const envKey = env.URL302 ? 'URL302' : (env.URL ? 'URL' : null);
			if (envKey) {
				const URLs = await ADD(env[envKey]);
				const URL = URLs[Math.floor(Math.random() * URLs.length)];
				return envKey === 'URL302' ? Response.redirect(URL, 302) : fetch(new Request(URL, request));
			}
			//首页改成一个nginx伪装页
			return new Response(await nginx(), {
				headers: {
					'Content-Type': 'text/html; charset=UTF-8',
				},
			});
		}
	}
};

async function nginx() {
	const text = `
	<!DOCTYPE html>
	<html>
	<head>
	<title>Welcome to nginx!</title>
	<style>
		body {
			width: 35em;
			margin: 0 auto;
			font-family: Tahoma, Verdana, Arial, sans-serif;
		}
	</style>
	</head>
	<body>
	<h1>Welcome to nginx!</h1>
	<p>If you see this page, the nginx web server is successfully installed and
	working. Further configuration is required.</p>
	
	<p>For online documentation and support please refer to
	<a href="http://nginx.org/">nginx.org</a>.<br/>
	Commercial support is available at
	<a href="http://nginx.com/">nginx.com</a>.</p>
	
	<p><em>Thank you for using nginx.</em></p>
	</body>
	</html>
	`
	return text;
}

async function ADD(envadd) {
	var addtext = envadd.replace(/[	|"'\r\n]+/g, ',').replace(/,+/g, ',');	// 将空格、双引号、单引号和换行符替换为逗号
	//console.log(addtext);
	if (addtext.charAt(0) == ',') addtext = addtext.slice(1);
	if (addtext.charAt(addtext.length - 1) == ',') addtext = addtext.slice(0, addtext.length - 1);
	const add = addtext.split(',');
	//console.log(add);
	return add;
}